import { paper as PaperApi, question as QuestionApi } from '../../../../../config/request.js';
import {
    resources,
    excelUtil as ExcelUtil
} from '../../../../../util';

module.exports = {
    name: 'pager',
    data() {
        return {
            downloadName: '试卷模板列表-' + new Date().getTime() + '.xlsx',
            questions: [],
            tableData: [],
            codeData: {},
            dialogVisible: false,
            codeVisible: false,
            pagerData: {},
            fields: [{
                    info: { prop: 'id', label: '试卷id', sortable: true },
                    filter: {},
                    style: { align: 'center' }
                },
                {
                    info: { prop: 'name', label: '试卷名称', sortable: false },
                    filter: {},
                    style: { align: 'center' }
                },
                // {
                //     info: { prop: 'block', label: '试卷内容', sortable: false },
                //     filter: {},
                //     style: { align: 'center' }
                // },
                // {
                //     info: { prop: 'relation', label: '关联', sortable: false },
                //     filter: {},
                //     style: { align: 'center' }
                // },
                {
                    info: { prop: 'remark', label: '备注', sortable: false },
                    filter: {},
                    style: { align: 'center' }
                }
            ]
        }
    },

    methods: {
        downloadExl(type) {
            if (type == 1) {
                this.downloadName = '所有模板-' + new Date().getTime() + '.xlsx';
                var tableData = this.tableData;
                var data = ExcelUtil.formatterData(tableData, ['relation', 'status', 'block']);
                ExcelUtil.downloadExl(this.downloadName, data);
            } else if (type == 2) {
                this.downloadName = this.pagerData.name + '-' + new Date().getTime() + '.xlsx';
                var tableData = this.formatterPagerData(this.pagerData);
                var data = ExcelUtil.formatterData(tableData, [], { 'qnumber': '题号', 'type': '题目类型', 'main': '题干', 'answers': '选项' });
                ExcelUtil.downloadExl(this.downloadName, data);
            }
        },
        formatterPagerData(pagerData) {
            var tableData = [];
            var blocks = pagerData.blocks;
            for (var i = 0; i < blocks.length; i++) {
                var questions = blocks[i]['questions'];
                for (var j = 0; j < questions.length; j++) {
                    var question = questions[j];
                    var answers = question['answers'];
                    var string = '';
                    if (answers) {
                        for (var z = 0; z < answers.length; z++) {
                            var answer = answers[z];
                            string += ('选项' + (z + 1) + ':' + answer.main + ';')
                        }
                    }
                    tableData.push({
                        'qnumber': (i + 1) + '-' + (j + 1),
                        'type': question.type,
                        'main': question.main,
                        'answers': string
                    });
                }
            }
            return tableData;
        },
        onAddPaper() {
            this.$router.push('/business/template/papers/edit');
        },

        onDeletePager(question) {
            // console.log(question);
            this.$confirm('是否确认删除该题目？', '提示', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning'
            }).then(_ => {
                PaperApi.deleteQuestion.call(this, question.id, (result) => {
                    let index = this.tableData.indexOf(question)
                    if (index !== -1) {
                        this.tableData.splice(index, 1);
                    }
                    this.$message.success('删除成功 ？');
                })
            }).catch((err) => {
                this.$message.error(err);
            });
        },

        onEditPaper(paper) {
            if (paper && paper.id) {
                this.$router.push('/business/template/papers/edit?id=' + paper.id);
            } else {
                this.$message({
                    showClose: true,
                    message: 'ID跑哪去了？',
                    type: 'error'
                });
            }
        },
        previewPager(paper) {
            var relation = JSON.parse(paper.relation);
            var relationFlag = relation.has_relation;
            if (relationFlag) {
                relation.relations.forEach(function(relationInfo) {
                    var question = this.findByQid(relationInfo.next_id);
                    question.hasRelation = true;
                    const preQuestion = this.findByQid(relationInfo.pre_ids[0]);
                    var relationDescribe = '要显示该题必须用户选择  <' + preQuestion.label + '> 的';
                    const options = JSON.parse(preQuestion.options);
                    options.forEach(function(option) {
                        if (option.id == relationInfo.pre_ids[1]) {
                            relationDescribe += (' ( ' + option.value + ' ) 选项');
                        }
                    }, this);
                    question.relationDescribe = relationDescribe;
                }, this);
            }

            var pagerData = {
                name: paper.name,
                id: paper.id,
                createdAt: paper.createdAt.replace('.000Z', '').replace('T', ':'),
                updatedAt: paper.updatedAt.replace('.000Z', '').replace('T', ':')
            };
            let blockArray = JSON.parse(paper.block);
            let blocks = [];
            blockArray.forEach(function(blockObj) {
                const questions = [];

                blockObj.questionId.forEach(function(qid) {
                    const answers = [];
                    const questionObj = this.findByQid(qid);
                    const answersArray = JSON.parse(questionObj.options);

                    answersArray.forEach(function(option) {
                        answers.push({
                            checked: option.checked,
                            main: option.value,
                            id: option.id,
                            hasScore: option.hasScore,
                            score: option.score
                        });
                    }, this);

                    questions.push({
                        main: questionObj.label,
                        id: questionObj.key,
                        type: resources.formatterQtype(questionObj.type),
                        answers: answers,
                        hasRelation: relationFlag && questionObj.hasRelation,
                        relationDescribe: questionObj.relationDescribe
                    });
                }, this);
                blocks.push({ name: blockObj.name, questions: questions });
            }, this);
            pagerData.blocks = blocks;
            this.pagerData = pagerData;
            this.dialogVisible = true;
        },
        previewCode(paper) {
            // console.log(paper);
            this.codeData = { block: paper.block, relation: paper.relation };
            this.codeVisible = true;
        },
        initData() {
            PaperApi.queryAll.call(this, (data) => {
                // console.log(data);
                this.tableData = data.papers;
            })
        },
        /**
         * 通过key找到问题对象
         * 
         * @param {any} key 
         * @returns 
         */
        findByQid(qid) {
            for (let i in this.questions) {
                if (qid == this.questions[i].key) {
                    return this.questions[i];
                }
            }
        },
        checkLevel() {
            var user = this.$store.state.user.userinfo;
            // console.log('user', user);
            return user && user.level == 1;
        },
    },
    created: function() {
        QuestionApi.queryAll.call(this, (data) => {
            let _q = data.questions;
            let questData = [];
            for (let index in _q) {
                questData.push({
                    key: _q[index].id,
                    label: _q[index].main,
                    options: _q[index].options,
                    type: _q[index].type
                });
            }

            this.questions = questData;
        })
    },

    mounted: function() {
        this.initData();
    }
}